package com.kgc.scd.config;


import com.kgc.scd.Constant.AccountMQConstant;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created On : 2022/11/10.
 * <p>
 * Author : zhukang
 * <p>
 * Description: 账务模块消息队列自动配置类，自动创建队列，交换机，并将队列绑定到交换机
 */
@Configuration
public class AccountMQConfig {

    /**
     * @author : zhukang
     * @date   : 2022/11/10
     * @param  : []
     * @return : org.springframework.amqp.core.Queue
     * @description : 创建支付结果通知订单中心队列
     */
    @Bean
    public Queue payResult2OrderQueue(){
        return new Queue(AccountMQConstant.NORMAL_PAY_RESULT_ORDER_QUEUE_TEST, true);
    }
    /**
     * @author : zhukang
     * @date   : 2022/11/10
     * @param  : []
     * @return : org.springframework.amqp.core.FanoutExchange
     * @description : 创建支付结果通知交换机
     */
    @Bean
    public FanoutExchange payResultExchange(){
        return new FanoutExchange(AccountMQConstant.NORMAL_PAY_RESULT_EXCHANGE_TEST);
    }

    /**
     * @author : zhukang
     * @date   : 2022/11/10
     * @param  : []
     * @return : org.springframework.amqp.core.Binding
     * @description : 绑定支付结果通知订单中心队列到支付结果通知交换机，不需要指定路由键
     */
    @Bean
    public Binding fanoutBindingQueueOne(){
        // 绑定队列到扇形交换机，不需要路由键，消息是广播式发送，交换机收到消息后，会给所有绑定的队列群发消息（根本没有提供with方法）
        return BindingBuilder.bind(payResult2OrderQueue()).to(payResultExchange());
    }

    /**
     * @author : zhukang
     * @date   : 2022/11/11
     * @param  : [connectionFactory]
     * @return : org.springframework.amqp.rabbit.core.RabbitAdmin
     * @description : 初始化RabbitAdmin对象，实现启动项目自动创建队列和交换机
     */
    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory){
        // 创建RabbitAdmin对象
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);

        // 设置启动时自动创建
        rabbitAdmin.setAutoStartup(true);

        // 创建需要使用交换机和队列
        rabbitAdmin.declareQueue(payResult2OrderQueue());
        rabbitAdmin.declareExchange(payResultExchange());

        // 返回对象
        return rabbitAdmin;
    }

}
